package com.tarena.rocketmq.sequence;

import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import static org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus.SUCCESS;

@Slf4j
public class SequenceConsumer {
    public static void main(String[] args) {
        //1.创建默认rocketmq消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("sequence-group-consume");
        consumer.setNamesrvAddr("localhost:9876");
        //2.订阅主题
        try {
            consumer.subscribe("sequence-topic","*");
        }catch (Exception e){
            log.error("订阅主题失败",e);
        }
        //3.绑定监听器
        MessageListenerOrderly listener=new MessageListenerOrderly() {
            @Override public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                log.info("收到消息个数：{}",msgs.size());
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                for (MessageExt msg:msgs){
                    log.info("收到消息：{}",new String(msg.getBody()));
                }
                //return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                return SUCCESS;
            }
        };
        //4.启动消费者
        try {
            consumer.registerMessageListener(listener);
            consumer.start();
        }catch (Exception e){
            log.error("启动消费者失败",e);
        }
    }
}
